import 'dart:async';

import 'package:fl_dit_verify/fl_dit_verify.dart';
import 'package:fl_dit_verify/umeng_verify_sdk.dart';
import 'package:fl_dit_verify_example/main.dart';
import 'package:fl_dit_verify_example/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return MainPageState();
  }
}

class MainPageState extends State<MainPage> {
  String _platformVersion = 'Unknown';
  final _flDitVerifyPlugin = FlDitVerify();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Column(
        children: [
          Text('Running on: $_platformVersion\n'),
          const SizedBox(
            height: 20,
          ),
          MaterialButton(
            onPressed: () {
              initVerify((token) {
                showLog('一键登录返回token= $token');
                if (Device.isAndroid) {
                  UmengVerifySdk.quitLoginPage_android();
                }
                UmengVerifySdk.cancelLoginVCAnimated(true);
              });
            },
            child: Container(
              height: 45,
              width: 200,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Colors.yellowAccent,
                  borderRadius: BorderRadius.circular(15)),
              child: const Text('点击初始化Verify Plugin'),
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          MaterialButton(
            onPressed: () {
              login();
            },
            child: Container(
              height: 45,
              width: 200,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Colors.yellowAccent,
                  borderRadius: BorderRadius.circular(15)),
              child: const Text('一键登录'),
            ),
          )
        ],
      ),
    );
  }

  bool isVerify = false;

  /// 一键认证
  initVerify(Function(String result) callback) {
    if (isVerify) {
      return;
    }
    showLog('------初始化-一键认证------');
    isVerify = true;
    showLog('register UmengCommonSdk for verify');
    UmengCommonSdk.initCommon(VerifyConfig.androidVerifyAppKey,
        VerifyConfig.iosVerifyAppKey, 'diting');
    if (Device.isAndroid) {
      showLog('register android for verify');
      UmengVerifySdk.register_android();
    }
    UmengVerifySdk.setVerifySDKInfo(
        VerifyConfig.androidAppSecret, VerifyConfig.iosAppSecret)
        .then((map) {
      showLog("=========初始化一键登录SDK回调:${map}");
    });
    if (Device.isAndroid) {
      UmengVerifySdk.setTokenResultCallback_android((result) {
        showLog("===============setTokenResultCallback_android:${result}");
        switch (result["code"]) {
          case "600001":
          //授权页成功唤起
            break;
          case "600000":
          //获取token 点击一键登录后返回
            callback.call(result["token"]);
            break;
          case "700000":
          //关闭授权页
            UmengVerifySdk.cancelLoginVCAnimated(true);
            break;
          case "700001":
          //切换到其他方式
            UmengVerifySdk.cancelLoginVCAnimated(true);
            break;
          case "700002":
            break;
          default:
          //其他错误
            UmengVerifySdk.hideLoginLoading();
            Fluttertoast.showToast(
                msg: result["msg"], toastLength: Toast.LENGTH_SHORT);
            break;
        }
      });
    } else {
      ///ios
      UmengVerifySdk.getLoginTokenCallback((result) {
        showLog("===============getLoginTokenCallback :${result}");

        switch (result["resultCode"]) {
          case "600001":
          //授权页成功唤起
            break;
          case "600000":
          //获取token 点击一键登录后返回
            callback.call(result["token"]);
            break;
          case "700000":
          //关闭授权页
            UmengVerifySdk.cancelLoginVCAnimated(true);
            break;
          case "700001":
          //切换到其他方式
            UmengVerifySdk.cancelLoginVCAnimated(true);
            break;
          case "700002":
          //点击登录按钮
            if (result["isChecked"] == false) {
              Fluttertoast.showToast(
                  msg: "请同意服务条款", toastLength: Toast.LENGTH_SHORT);
            }
            break;
          case "700003":
          //点击了协议CheckBox按钮
            break;
          default:
          //其他错误
            UmengVerifySdk.hideLoginLoading();
            Fluttertoast.showToast(
                msg: result["msg"], toastLength: Toast.LENGTH_SHORT);
            break;
        }
      });
    }
  }

  login() {
    UMCustomModel uiConfig = UMCustomModel();
    if (Device.isAndroid) {
      uiConfig.navIsHidden = true;
      uiConfig.loginBtnText = ["本机号码一键登录", Colors.white.value, 16.sp];
      uiConfig.loginBtnBgImg_android = "login_button_bg";
      uiConfig.logoImage = 'logo';
      uiConfig.autoHideLoginLoading = false;
      // uiConfig.privacyOne = ["协议1", "https://www.umeng.com"];
      uiConfig.privacyColors = [Color_999.value, Color_Main.value];
      uiConfig.logoFrame = [100.sp, -1, 78.sp, 78.sp];
      uiConfig.sloganText = ["由中国移动提供认证服务", Color_999.value, 12.sp];
      uiConfig.sloganFrame = [240.sp, -1, -1, -1];
      uiConfig.numberFrame = [-1, 260.sp, -1, -1];
      uiConfig.loginBtnFrame = [-1, 380.sp, -1, -1, -1];
      uiConfig.changeBtnFrame = [450.sp, -1, -1, -1];
      uiConfig.changeBtnTitle = ["切换到其他方式", Color_Main.value, 12.sp];
      uiConfig.checkBoxImages = ["login_unselect_icon", "login_select_icon"];
      uiConfig.checkBoxWH = 16.sp;
      UMCustomWidget customTextView =
      UMCustomWidget("textView", UMCustomWidgetType.textView);
      customTextView.title = "若该手机号未注册，我们会自动为您注册";
      customTextView.textAlignment = UMCustomWidgetTextAlignmentType.center;
      customTextView.titleColor = Color_999.value;
      customTextView.titleFont = 12.sp;
      customTextView.top = 300.sp.toInt();
      customTextView.width = Get.width.toInt();
      uiConfig.customWidget = [
        customTextView.toJsonMap(),
      ];
    } else {
      uiConfig.navIsHidden = true;
      uiConfig.loginBtnText = ["本机号码一键登录", Colors.white.value, 16.sp];
      uiConfig.loginBtnBgImgs_ios = [
        "login_button_bg",
        "login_button_bg",
        "login_button_bg"
      ];
      uiConfig.loginBtnFrame = [
        20.w,
        Get.height / 2,
        -1,
        Get.width - 40.w,
        50.sp
      ];
      uiConfig.logoImage = "logo";
      uiConfig.logoFrame = [Get.width / 2 - 38.sp, 100, 76.sp, 76.sp];
      uiConfig.autoHideLoginLoading = false;
      uiConfig.privacyAlignment = UMTextAlignment.Center;
      uiConfig.privacyColors = [Color_999.value, Color_Main.value];
      uiConfig.sloganText = ["由中国移动提供认证服务", Color_999.value, 12.sp];
      uiConfig.sloganFrame = [0, Get.height / 4, Get.width, 80.sp];
      uiConfig.checkBoxImages = ["login_unselect_icon", "login_select_icon"];
      uiConfig.checkBoxWH = 20.sp;
      uiConfig.changeBtnTitle = ["切换到其他方式", Color_Main.value, 12.sp];
      uiConfig.changeBtnFrame = [
        0,
        Get.height / 2 + 80.h.toInt(),
        Get.width,
        20.w
      ];

      UMCustomWidget customTextView =
      UMCustomWidget("textView", UMCustomWidgetType.textView);
      customTextView.title = "若该手机号未注册，我们会自动为您注册";
      customTextView.textAlignment = UMCustomWidgetTextAlignmentType.center;
      customTextView.titleColor = Color_999.value;
      customTextView.titleFont = 12.sp;
      customTextView.width = Get.width.toInt();
      customTextView.height = 20;
      customTextView.top = Get.height ~/ 2 - 90.h.toInt();
      uiConfig.customWidget = [
        customTextView.toJsonMap(),
      ];
    }

    UmengVerifySdk.accelerateLoginPageWithTimeout(3).then((result) {
      showLog("登录加速结果 $result");
      UmengVerifySdk.getLoginTokenWithTimeout(3, uiConfig);
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _flDitVerifyPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }
}
